import React, { Component } from 'react'
import { connect } from 'react-redux';
const Cart = class Cart extends Component {

  render() {
    let { list } = this.props;
    let cartList = [];
    Object.keys(list).forEach((type) => {
      list[type].forEach((item) => {
        if (item.num > 0) {
          cartList.push(item);
        }
      })
    })
    return (
      <div>
        购物车

        <ul>
          {cartList.map((v) => {
            return <li key={v.id}>{v.name}
              <p>库存: {v.stock}</p>

              <p><span onClick={() => {
                v.num--;
                if (v.num < 0) {
                  v.num = 0;
                }
                this.props.setList(list);
              }}>-</span>{v.num}<span onClick={() => {
                if (v.stock > 0) {
                  v.num++;
                  v.stock--;
                }
                this.props.setList(list);

              }}>+</span></p>
            </li>
          })}
        </ul>
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    ...state
  };
}
const mapDispatchToProps = (dispatch) => {
  return {
    setList(data) {
      dispatch({ type: 'SET_LIST', data })
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Cart);
